﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using VanTaiBLL;
using VanTaiProperty;
using System.Text;
using System.Web.UI.HtmlControls;
using Roles;
namespace VanTaiTMS.Page
{
    public partial class danh_muc_khoan : System.Web.UI.Page
    {
        #region[Define]
        private static bool _flag;
        private DataTable dtCabin;
        private DataTable dtCabinDetail;
        private DataTable dtVehicle;
        protected string StrAlert = "";
        public string SuggestionList = "";
        private DataTable _dtAutoComplete;
        private DataTable _dtSearch;
        private TMCabin_Business clsCabin = new TMCabin_Business();
        private clsTMVehicleBusiness clsVehicle = new clsTMVehicleBusiness();
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            Autocomplete();
            if (!IsPostBack)
            {
                BindGirdCabin();
                BindGridVehicle();
            }
        }
        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            _flag = true;
            lbThongBaoLoi.Text = "";
            txtMaCabin.Enabled = true;
            ClearTextbox();
            OpenDialog("#cabin");
            imgSave.ToolTip = "Thêm mới";
            upNewUpdatePanel.Update();
            imgSave.Visible = true;
        }
        protected void cmdEdit_Click(object sender, EventArgs e)
        {
            lbThongBaoLoi.Text = "";
            txtMaCabin.Enabled = false;
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                var chkView = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                if (chkView != null)
                {
                    if (chkView.Checked)
                    {
                        var dataKey = ListViewAll.DataKeys[i];
                        if (dataKey != null)
                            lbIDXoa.Text = dataKey.Value.ToString();
                        OpenDialog("#cabin");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        _flag = false;
                    }
                }
            }
        }
        protected void cmdDel_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                var chkHide = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                if (chkHide != null)
                {
                    if (chkHide.Checked)
                    {
                        try
                        {
                            var dataKey = ListViewAll.DataKeys[i];
                            if (dataKey != null)
                                TMCabin_Business.DeleteCabin(int.Parse(dataKey.Value.ToString()));
                        }
                        catch (Exception)
                        {
                            lbThongBaoXoa.Text = "Mẫu tin này vẩn còn tồn tại.Không thể xoá !";
                            OpenDialog("#thongbaoxoa");
                            upDatePanelThongBaoXoa.Update();
                            cmdAgree.Visible = false;
                            cmdClose.Text = "Đóng lại";
                        }
                    }
                }
            }
        }
        protected void cmdSerach_Click(object sender, EventArgs e)
        {
            if (txtSearch.Text == "")
            {
                StrAlert += "<div class='alert alert-warning'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Vui lòng nhập vào từ khoá để tìm kiếm !";
                StrAlert += "</div>";
            }
            else
            {
                Search(txtSearch.Text);
            }
        }
        protected void cmdRefesh_Click(object sender, EventArgs e)
        {
            txtSearch.Text = "";
            BindGirdCabin();
        }
        //---------------button-popup---------------------
        protected void imgrefesh_Click(object sender, ImageClickEventArgs e)
        {
        }
        protected void imgSave_Click(object sender, ImageClickEventArgs e)
        {
            if (txtMaCabin.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào mã Cabin !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtTenCabin.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào tên Cabin !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtChieuDai.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào chiều dài !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtChieuRong.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào chiều rộng !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtChieuCao.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào chiều cao !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drChooseCarNumber.SelectedValue.ToString() =="-1")
            {
                lbThongBaoLoi.Text = "Vui lòng điền chọn số xe !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtMaCabin.Text != "" && txtTenCabin.Text != ""
            && txtChieuCao.Text != "" && txtChieuDai.Text != "" && txtChieuRong.Text != ""
            && drChooseCarNumber.SelectedValue.ToString() != "-1")
            {
                Insert();
            }
        }
        protected void cmdAgree_Click(object sender, EventArgs e)
        {

        }
        protected void cmdClose_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbaoxoa");
        }
        protected void cmdCloseThongBao_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbao");
        }
        //-------------list-view-----------------------
        protected void ListViewAll_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                HttpCookie cookie = Request.Cookies["UserLogin"];
                bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLyDanToc, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                lbThongBaoLoi.Text = "";
                txtMaCabin.Enabled = false;
                if (e.CommandName == "Accept")
                {
                    if (Edit == false)
                    {
                        imgSave.Visible = false;
                        string senderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGirdCabinEdit(int.Parse(senderId));
                        OpenDialog("#cabin");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        _flag = false;
                    }
                    else
                    {
                        imgSave.Visible = true;
                        string senderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGirdCabinEdit(int.Parse(senderId));
                        OpenDialog("#cabin");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        _flag = false;
                    }
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void ListViewAll_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                var linkName = (LinkButton)e.Item.FindControl("linkTenDanToc");
                string jsDouble = ClientScript.GetPostBackClientHyperlink(linkName, "");
                linkName.Attributes["ondblclick"] = jsDouble;
                linkName.Attributes["onclick"] = "return false;";
            }
        }
        //-----------pagger-----------------------
        protected void DataPagerListAll_PreRender(object sender, EventArgs e)
        {
            DataPagerListAll.PageSize = 17;
            BindGirdCabin();
        }
        #endregion

        #region[Function]
        protected void BindGirdCabin()
        {
            dtCabin = clsCabin.Search(txtSearch.Text);
            if (dtCabin != null && dtCabin.Rows.Count > 0)
            {
                ListViewAll.DataSource = dtCabin;
                ListViewAll.DataBind();
                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;
            }
            else
            {
                ListViewAll.Visible = false;
                DataPagerListAll.Visible = false;
            }
        }
        protected void BindGirdCabinEdit(int id)
        {
            dtCabinDetail = clsCabin.BindCabinDetail(id);
            if (dtCabinDetail != null && dtCabinDetail.Rows.Count > 0)
            {
                lbID.Text = dtCabinDetail.Rows[0]["Cabin_Id"].ToString();
                lbIDXoa.Text = dtCabinDetail.Rows[0]["Cabin_Id"].ToString();
                txtMaCabin.Text = dtCabinDetail.Rows[0]["Cabin_Alias"].ToString();
                txtTenCabin.Text = dtCabinDetail.Rows[0]["Cabin_Name"].ToString();
                txtChieuDai.Text = dtCabinDetail.Rows[0]["Cabin_Length"].ToString();
                txtChieuRong.Text = dtCabinDetail.Rows[0]["Cabin_Width"].ToString();
                txtChieuCao.Text = dtCabinDetail.Rows[0]["Cabin_Height"].ToString();
                drChooseCarNumber.SelectedValue = dtCabinDetail.Rows[0]["Vehicle_ID"].ToString();
            }
        }
        protected void BindGridVehicle()
        {
            dtVehicle = clsVehicle.BindGirdTMVehicle();
            if (dtVehicle != null && dtVehicle.Rows.Count > 0)
            {
                drChooseCarNumber.DataSource = dtVehicle;
                drChooseCarNumber.DataTextField = "Vehicle_Number";
                drChooseCarNumber.DataValueField = "Vehicle_ID";
                drChooseCarNumber.DataBind();
            }
        }
        protected void Insert()
        {
            //Insert
            if (_flag)
            {
                InsertCabin();
            }
            else //Update
            {
                UpdateCabin();
            }
        }
        protected bool CheckInsert()
        {
            bool kiemtra = false;
            dtCabin = clsCabin.BindCabin();
            if (dtCabin != null && dtCabin.Rows.Count > 0)
            {
                foreach (DataRow dr in dtCabin.Rows)
                {
                    if (txtMaCabin.Text == dr["Cabin_Alias"].ToString())
                    {
                        kiemtra = true;
                    }
                }
            }
            return kiemtra;
        }
        protected void InsertCabin()
        {
            try
            {
                if (CheckInsert())
                {
                    lbThongBaoLoi.Text = "Mã Cabin đã tồn tại !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                }
                else
                {
                    TMCabin_Property obj = new TMCabin_Property();
                    obj.Cabin_Alias = txtMaCabin.Text;
                    obj.Vehicle_ID = int.Parse(drChooseCarNumber.SelectedValue.ToString());
                    obj.Cabin_Name = txtTenCabin.Text;
                    obj.Cabin_Length = float.Parse(txtChieuDai.Text);
                    obj.Cabin_Width = float.Parse(txtChieuRong.Text);
                    obj.Cabin_Height = float.Parse(txtChieuCao.Text);
                    obj.Cabin_Total = float.Parse(txtChieuCao.Text) + float.Parse(txtChieuRong.Text) + float.Parse(txtChieuDai.Text);
                    VanTaiBLL.TMCabin_Business.InsertCabin(obj);
                    BindGirdCabin();
                    lbThongBaoLoi.Text = "Thêm mới thành công Cabin !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                }
            }
            catch(Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void UpdateCabin()
        {
            try
            {
                VanTaiProperty.TMCabin_Property obj = new VanTaiProperty.TMCabin_Property();
                obj.Cabin_Id = int.Parse(lbID.Text);
                obj.Cabin_Alias = txtMaCabin.Text;
                obj.Vehicle_ID = int.Parse(drChooseCarNumber.SelectedValue.ToString());
                obj.Cabin_Name = txtTenCabin.Text;
                obj.Cabin_Length = float.Parse(txtChieuDai.Text);
                obj.Cabin_Width = float.Parse(txtChieuRong.Text);
                obj.Cabin_Height = float.Parse(txtChieuCao.Text);
                obj.Cabin_Total = float.Parse(txtChieuCao.Text) + float.Parse(txtChieuRong.Text) + float.Parse(txtChieuDai.Text);
                VanTaiBLL.TMCabin_Business.UpdateCabin(obj);
                BindGirdCabin();
                lbThongBaoLoi.Text = "Cập nhật thành công Cabin !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        //Search
        protected void Search(string keywords)
        {
            _dtSearch = clsCabin.Search(txtSearch.Text);
            if (_dtSearch != null && _dtSearch.Rows.Count > 0)
            {
                ListViewAll.DataSource = _dtSearch;
                ListViewAll.DataBind();
                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;

                StrAlert += "<div class='alert alert-success'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Tìm thấy " + _dtSearch.Rows.Count + " mẫu tin !";
                StrAlert += "</div>";
            }
            else
            {
                ListViewAll.Visible = false;
                DataPagerListAll.Visible = false;
                StrAlert += "<div class='alert alert-error'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Không tìm thấy mẫu tin nào !";
                StrAlert += "</div>";
            }
        }
        //Autocomplete
        protected void Autocomplete()
        {
            _dtAutoComplete = clsCabin.BindCabin();
            if (_dtAutoComplete != null && _dtAutoComplete.Rows.Count > 0)
            {
                foreach (DataRow dr in _dtAutoComplete.Rows)
                {
                    if (string.IsNullOrEmpty(SuggestionList))
                    {
                        SuggestionList += "\"" + dr["Cabin_Name"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["Cabin_Alias"].ToString().Replace("\n", " ") + "\",";
                    }
                    else
                    {
                        SuggestionList += "\"" + dr["Cabin_Name"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["Cabin_Alias"].ToString().Replace("\n", " ") + "\",";
                    }
                }
            }
        }
        #endregion

        #region[ClearTextBox]
        protected void ClearTextbox()
        {
            txtMaCabin.Text = string.Empty;
            txtTenCabin.Text = string.Empty;
            txtChieuDai.Text = "0";
            txtChieuRong.Text = "0";
            txtChieuCao.Text = "0";

            drChooseCarNumber.SelectedIndex = -1;
        }

        #endregion

        #region[OpenDialog]
        private void OpenDialog(string dialogId)
        {
            var sb = new StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('open');");
            ScriptManager.RegisterStartupScript(Page, Page.GetType(),
                "scriptKey", sb.ToString(), true);
        }
        private void CloseDialog(string dialogId)
        {
            var sb = new StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('close');");
            ScriptManager.RegisterStartupScript(Page, Page.GetType(),
                "scriptKey", sb.ToString(), true);
        }

        #endregion
    }
}